﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Gao.Poker.Domain;

namespace Gao.Poker.Services
{
    public class ProductService : BaseService
    {
        private static ProductService _Instance;

        public static ProductService Instance()
        {
            return _Instance ?? (_Instance = new ProductService());
        }

        public List<Product> SearchProducts(String productName)
        {
            return DbContext.Products.Where(a => a.ProductName.Contains(productName)).ToList();
        }

        /// <summary>
        /// 搜素商品
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="barCode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<Product> SearchProducts(String productName, String barCode, int pageIndex, int pageSize)
        {
            return DbContext.Products.Where(a => a.ProductName.Contains(productName))
                .Where(a => a.BarCode.Contains(barCode))
                .OrderBy(a => a.ID)
                .Skip(pageIndex * pageSize)
                .Take(pageSize).ToList();
        }

        public int GetProductTotal(String productName, String barCode)
        {
            return
                DbContext.Products.Where(a => a.ProductName.Contains(productName)).Count(a => a.BarCode.Contains(barCode));
        }

        public Product GetProduct(String barCode)
        {
            return DbContext.Products.FirstOrDefault(a => a.BarCode.Equals(barCode));
        }

        public Product Save(Product product)
        {
            if (product == null) return null;

            if (product.ID == 0)
            {
                DbContext.Products.Add(product);
            }
            else
            {
                DbContext.Products.Attach(product);
                DbContext.Entry(product).State = EntityState.Modified;
            }

            Trace.WriteLine(DbContext.ToString());
            DbContext.SaveChanges();
            return product;
        }
        /// <summary>
        /// Delete a record of goods
        /// </summary>
        /// <param name="product"></param>
        public void Delete(Product product)
        {
            if (product == null) return;

            var p = DbContext.Products.Find(product.ID);
            DbContext.Products.Remove(p);
            DbContext.SaveChanges();
        }
    }
}
